package cn.wk.libs4a.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PixelFormat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import cn.wk.libs4a.R;
import cn.wk.libs4a.view.phonecontact.WKPhoneContactUtils;

/**
 * 字母导航
 */
public class WKABCSideBar extends View implements OnTouchListener {
	private Context context;
	private List<Character> lettersList;// listview数据首字母
	private List<Character> letters;// 右边显示的列表
	private int currentItem = 0;// 当前选中的字母索引
	private WindowManager mWindowManager;
	private TextView mDialogText;// 用于中间显示当前选中的字母
	private ListView listView;// 联系人列表

	private int unSelectColor = 0xff858c94;
	private int selectColor = Color.RED;

	private IWKABCSideBar iWKABCSideBar = null;

	private boolean isInitOK = false;

	public WKABCSideBar(Context context) {
		this(context, null);
	}

	public WKABCSideBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
	}

	/**
	 * 设置char列表
	 * 
	 * @param list
	 */
	public void setCharList(ArrayList<Character> list) {
		this.lettersList = list;
	}

	/**
	 * 初始化是必须的，且在数据准备好之后
	 */
	public void init(IWKABCSideBar bar, ListView l) {
		if (isInitOK) {
			return;
		}
		isInitOK = true;

		this.iWKABCSideBar = bar;
		selectColor = getResources().getColor(R.color.app_green);

		letters = toList(new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
				'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
				'U', 'V', 'W', 'X', 'Y', 'Z', '#' });
		mDialogText = (TextView) LayoutInflater.from(context).inflate(
				R.layout.wk_sidebar_text_dialog, null);
		// View.INVISIBLE不可见，但这个View仍然会占用在xml文件中所分配的布局空间，不重新layout
		mDialogText.setVisibility(View.INVISIBLE);
		mWindowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
						| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		mWindowManager.addView(mDialogText, lp);

		// 设置列表
		// 设置触摸事件
		this.setOnTouchListener(this);
		setListView(l);
	}

	protected void onDraw(Canvas canvas) {
		if (letters == null || letters.size() == 0)
			return;
		Paint paint = new Paint();
		paint.setTextSize(32);
		// paint.setTextSize(48);
		paint.setStyle(Style.FILL);
		// paint.setFakeBoldText(true);
		paint.setTextAlign(Paint.Align.CENTER);
		float widthCenter = getMeasuredWidth() / 2;
		float height = getMeasuredHeight() / letters.size();
		for (int i = 0; i < letters.size(); i++) {
			if (currentItem == i) {
				paint.setColor(selectColor);
			} else {
				paint.setColor(unSelectColor);
			}

			canvas.drawText(String.valueOf(letters.get(i)), widthCenter,
					(i + 1) * height, paint);
		}
	}

	boolean isOnTouch = false;

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:// 手机点下时
		case MotionEvent.ACTION_MOVE:// 手机触摸移动时
			isOnTouch = true;
			// 计算点击的是哪一个字母
			int y = (int) event.getY();
			currentItem = y / (getMeasuredHeight() / letters.size());
			if (currentItem >= letters.size()) {
				currentItem = letters.size() - 1;
			} else if (currentItem < 0) {
				currentItem = 0;
			}
			mDialogText.setText(letters.get(currentItem) + "");
			mDialogText.setVisibility(View.VISIBLE);
			this.setBackgroundColor(Color.rgb(187, 187, 187));

			// 计算指定字母索引对应contacts中位置
			int listIndex = iWKABCSideBar.getSectionForPosition(letters
					.get(currentItem));
			if (listIndex != -1) {
				listView.setSelection(listIndex);
			}
			invalidate();

			break;
		case MotionEvent.ACTION_UP:// 手指离开屏幕时
			isOnTouch = false;
			mDialogText.setVisibility(View.INVISIBLE);
			this.setBackgroundColor(Color.TRANSPARENT);
			break;

		default:
			break;
		}

		return true;
	}

	public void setListView(ListView listView) {
		this.listView = listView;
		this.listView.setOnScrollListener(new OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				try {
					if (isOnTouch)
						return;
					// 当前ListView能显示第一行汉字首字母在letter中的位置
					String str = iWKABCSideBar.getFirstItem(firstVisibleItem);
					String firstZm = WKPhoneContactUtils.getPingYin(str)
							.toUpperCase();
					if (TextUtils.isEmpty(firstZm)) {
						currentItem = 0;
					} else {
						currentItem = letters.indexOf(firstZm.charAt(0));
					}
					WKABCSideBar.this.invalidate();
				} catch (Exception e) {
				}
			}
		});
	}

	/**
	 * 将数组添加到List
	 */
	private List<Character> toList(char[] letters) {
		if (letters == null || letters.length < 1) {
			return null;
		}
		List<Character> letterList = new ArrayList<Character>();
		for (char l : letters) {
			if (iWKABCSideBar.includeThisChar(l)) {
				letterList.add(l);
			}
		}
		return letterList;
	}

}
